﻿using Microsoft.SharePoint;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using VPLink2013.Framework;

namespace VPLink2014
{
    public class WidgetOperations
    {
        public static MeteoInfo GetMeteoInfoByUrl(string url)
        {
            MeteoInfo meteoInfo = new MeteoInfo();
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                WebRequest request = WebRequest.Create(url);
                if (request != null)
                {
                    request.Credentials = CredentialCache.DefaultCredentials;
                    WebResponse response = request.GetResponse();
                    if (response != null)
                    {
                        Stream dataStream = response.GetResponseStream();
                        if (dataStream != null)
                        {
                            XmlSerializer serializer = new XmlSerializer(typeof(MeteoInfo));
                            if (serializer != null)
                            {
                                meteoInfo = (MeteoInfo)serializer.Deserialize(dataStream);
                            }
                        }
                    }
                }
            });
            return meteoInfo;
        }

        private static void FillRerInfoList(string xPath, List<RerInfo> rerInfoList, WebResponse response)
        {
            Stream dataStream = response.GetResponseStream();
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.Load(dataStream, Encoding.UTF8);
            if (doc.DocumentNode.SelectNodes(xPath) != null)
            {
                foreach (HtmlAgilityPack.HtmlNode table in doc.DocumentNode.SelectNodes(xPath))
                {
                    foreach (HtmlAgilityPack.HtmlNode row in table.SelectNodes("tr"))
                    {
                        HtmlAgilityPack.HtmlNodeCollection cells = row.SelectNodes("td");
                        if (cells == null)
                        {
                            continue;
                        }
                        string nomRer = (cells[1] != null) ? cells[1].InnerText : string.Empty;
                        string horaire = (cells[2] != null) ? Regex.Replace(cells[2].InnerText, @"\s", string.Empty) : string.Empty;
                        string direction = (cells[3] != null) ? cells[3].InnerText : string.Empty;
                        string voie = (cells[5] != null) ? Regex.Replace(cells[5].InnerText, @"\s", string.Empty) : string.Empty;

                        rerInfoList.Add(new RerInfo()
                        {
                            Nom = nomRer,
                            Horaire = horaire,
                            Voie = voie,
                            Direction = direction
                        });
                    }
                }
            }
            response.Close();
        }

        public static MeteoInfo GetMeteoInfoByUrl(string url, string proxyAddress, string login, string pwd, string domain)
        {
            MeteoInfo meteoInfo = new MeteoInfo();
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                WebRequest request = WebRequest.Create(url);
                WebProxy proxy = new WebProxy(proxyAddress, true);
                proxy.Credentials = new NetworkCredential(login, pwd, domain);
                request.Proxy = proxy;
                request.Credentials = new NetworkCredential(login, pwd, domain);
                WebResponse response = request.GetResponse();
                Stream dataStream = response.GetResponseStream();
                XmlSerializer serializer = new XmlSerializer(typeof(MeteoInfo));
                meteoInfo = (MeteoInfo)serializer.Deserialize(dataStream);
            });
            return meteoInfo;
        }

        public static List<RerInfo> GetRerInfoByUrl(string url, string xPath, string proxyAddress, string login, string pwd, string domain)
        {
            List<RerInfo> rerInfoList = new List<RerInfo>();
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                WebRequest request = WebRequest.Create(url);
                WebProxy proxy = new WebProxy(proxyAddress, true);
                proxy.Credentials = new NetworkCredential(login, pwd, domain);
                request.Proxy = proxy;
                request.Credentials = new NetworkCredential(login, pwd, domain);
                WebResponse response = request.GetResponse();
                FillRerInfoList(xPath, rerInfoList, response);
            });
            return rerInfoList;
        }


        public static List<RerInfo> GetRerInfoByUrl(string url, string xPath)
        {
            List<RerInfo> rerInfoList = new List<RerInfo>();
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                WebRequest request = WebRequest.Create(url);
                request.Credentials = CredentialCache.DefaultCredentials;
                WebResponse response = request.GetResponse();
                FillRerInfoList(xPath, rerInfoList, response);
            });
            return rerInfoList;
        }
        public static RerAlert GetRerExtraInfo(string xpath, string xpathDetail, string urlInfo, string url, string proxyAddress, string login, string pwd, string domain)
        {
            RerAlert alert = new RerAlert();
            alert.exists = false;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                WebRequest request = WebRequest.Create(url);
                WebProxy proxy = new WebProxy(proxyAddress, true);
                proxy.Credentials = new NetworkCredential(login, pwd, domain);
                request.Proxy = proxy;
                request.Credentials = new NetworkCredential(login, pwd, domain);

                WebResponse response = request.GetResponse();
                FillRerExtraInfo(xpath, xpathDetail, urlInfo, alert, response);
            });
            return alert;
        }

        public static RerAlert GetRerExtraInfo(string xpath, string xpathDetail, string urlInfo, string url)
        {
            RerAlert alert = new RerAlert();
            alert.exists = false;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                WebRequest request = WebRequest.Create(url);
                request.Credentials = CredentialCache.DefaultCredentials;
                WebResponse response = request.GetResponse();
                FillRerExtraInfo(xpath, xpathDetail, urlInfo, alert, response);
            });
            return alert;
        }

        private static void FillRerExtraInfo(string xpath, string xpathDetail, string urlInfo, RerAlert alert, WebResponse response)
        {
            Stream dataStream = response.GetResponseStream();
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.Load(dataStream, Encoding.UTF8);

            //Info Alert
            /*<div class="icvPart icvPartNormal">
             * <ul>
             * <li class="icv">
             * <a href=""></a>
             * </li>
             * </ul>
             * </div>
             * */
            HtmlAgilityPack.HtmlNodeCollection divInf = doc.DocumentNode.SelectNodes(xpath);
            if (divInf != null)
            {
                // plus qu'une alerte
                if (divInf[0].SelectNodes("ul") != null)
                {
                    if (divInf[0].SelectNodes("ul").Count > 0)
                    {
                        var liInfo = divInf[0].SelectNodes("ul")[0].SelectNodes(xpathDetail);
                        alert.Description = liInfo[0].InnerText;
                        alert.Url = string.Format("{0}{1}", urlInfo, liInfo[0].SelectNodes("a")[0].Attributes["href"].Value);
                        alert.exists = true;
                    }
                }
            }
            response.Close();
        }
    }
}
